<template>
    <div :style="{marginTop:$store.state.navbarHeight+12+'rpx'}">
        <Navbar bgColor="bg-gradual-pink" :isSearch="true" />
        <div class="container" :style="{marginTop:customBar()*2+12+'rpx'}">
            <div class="swiper-wrap">
                <swiper indicator-active-color="rgba(255,255,255,.7)" :indicator-dots="true" autoplay :interval="5000" :duration="1000">
                    <div v-for="(item,index) in adList" :key="index" @click="toAd(item)">
                        <swiper-item>
                            <image :src="item.imgUrl" />
                        </swiper-item>
                    </div>
                </swiper>
            </div>
            <div class="recommend">
                <div class="more">
                    <span class="title">تەۋسىيە</span>
                    <span class="dot">
                        <!-- <i class="name">تېخىمۇ كۆپ</i>
                        <i class="myfont icon-arrow"></i> -->
                    </span>
                </div>
                <div class="list">
                    <VideoCover :scroll="scroll" v-for="item in allVideo.recommend" :key="item.vid" :info="item"></VideoCover>
                </div>
            </div>
            <ad unit-id="adunit-30186b9b0818886c"></ad>
            <div class="new-video">
                <div class="more" @click="getMore('new')">
                    <span class="title">يېڭى كىنولار</span>
                    <span class="dot">
                        <i>تېخىمۇ كۆپ</i>
                        <i class="myfont icon-arrow"></i>
                    </span>
                </div>
                <div class="list">
                    <VideoCover :scroll="scroll" v-for="item in allVideo.newList" :key="item.vid" :info="item"></VideoCover>
                </div>
            </div>
            <div class="hot-video">
                <div class="more" @click="getMore('hot')">
                    <span class="title">ئاۋات كىنولار</span>
                    <span class="dot">
                        <i>تېخىمۇ كۆپ</i>
                        <i class="myfont icon-arrow"></i>
                    </span>
                </div>
                <div class="list">
                    <VideoCover :scroll="scroll" v-for="item in allVideo.hotList" :key="item.vid" :info="item"></VideoCover>
                </div>
            </div>
            <div class="tv">
                <div class="more" @click="getMore('TV')">
                    <span class="title">قىسىملىق</span>
                    <span class="dot">
                        <i>تېخىمۇ كۆپ</i>
                        <i class="myfont icon-arrow"></i>
                    </span>
                </div>
                <div class="list">
                    <VideoCover :scroll="scroll" v-for="item in allVideo.tv" :key="item.vid" :info="item"></VideoCover>
                </div>

            </div>
            <!-- <div class="short-video">
                <div class="more" @click="getMore('SHORT')">
                    <span class="title">قىسقا ڧىلىملار</span>
                    <span class="dot">
                        <i>تېخىمۇ كۆپ</i>
                        <i class="myfont icon-arrow"></i>
                    </span>
                </div>
                <div class="list">
                    <VideoCover :scroll="scroll" v-for="item in allVideo.shortList" :key="item.vid" :info="item"></VideoCover>
                </div>
            </div> -->
            <div class="show">
                <div class="more" @click="getMore('VARIETY')">
                    <span class="title">سەنئەت</span>
                    <span class="dot">
                        <i>تېخىمۇ كۆپ</i>
                        <i class="myfont icon-arrow"></i>
                    </span>
                </div>
                <div class="list">
                    <VideoCover :scroll="scroll" v-for="item in allVideo.varietyList" :key="item.vid" :info="item"></VideoCover>
                </div>
            </div>

        </div>
        <div class="sign-in" v-if="signVisible">
            <form @submit="getFormId" report-submit>
                <button form-type='submit'>
                    <i>يوقلام</i>
                </button>
            </form>
        </div>
        <i-toast id="toast" />
        <Tabbar :selectNavIndex="0"></Tabbar>
        <!-- 广告 -->
        <div class="my-ad" @click="toMyAd" v-if="showMyAd&&$store.state.config.showAd">
            <!-- <div class="exit"></div> -->
            <image @click="toMyAd" :src="elan.imgUrl" class="elan"></image>
            <image @click="showMyAd=false" src="https://mars-kino.oss-cn-beijing.aliyuncs.com/static/%E5%85%B3%E9%97%AD.png" class="exit"></image>
        </div>
    </div>
</template>

<script>
import HelloWorld from "@/components/HelloWorld.vue";
import Tabbar from "@/components/Tabbar.vue";
import Navbar from "@/components/Navbar.vue";
import VideoCover from "@/components/VideoCover.vue";
let qcloud = require("wafer2-client-sdk");
import { Base64, $Toast, _decrypt, throttle } from "@/utils/index";
import { mapState, mapActions, mapGetters } from "vuex";
export default {
    onPageScroll(e) {
        // this.fnThrottle(this.onScroll, 500, 500, e)();
    },
    components: {
        HelloWorld,
        Tabbar,
        Navbar,
        VideoCover
    },
    data() {
        return {
            adList: [],
            allVideo: {},
            currentPage: 1,
            pageSize: 21,
            newlist: [],
            hotList: [],
            formId: {},
            signVisible: true,
            scroll: {},
            showMyAd: true,
            elan: {}
        };
    },
    async mounted() {
        this.init();
        this.getAdList();
        // 判断用户是否登陆
        let userInfo = wx.getStorageSync("userInfo");
        if (userInfo && userInfo.openId && userInfo.uid) {
            this.$store.commit("SET_USERINFO", userInfo);
        } else {
            if (this.$store.state.config.forceLogin) {
                wx.navigateTo({ url: "/pages/Login/Login" });
            } else {
            }
        }
        wx.showLoading();
        this.$http
            .get("/mpGetVideo", {
                currentPage: this.currentPage,
                pageSize: this.pageSize
            })
            .then(res => {
                wx.hideLoading();
                let listStr = res.list.replace(/\&/g, "A").replace(/\%/g, "B");
                let list = Base64.decode(listStr);
                list = JSON.parse(list);
                this.allVideo = list;
                // this.newlist = list.slice(0, 12);
                // this.hotList = list.slice(12, 21);
            })
            .catch(err => {
                wx.hideLoading();
            });
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo
        })
    },
    created() {
        wx.hideTabBar();
    },
    beforeMount() {
        // wx.navigateTo({ url: "/pages/Buy/Buy" });

        wx.hideTabBar();
    },
    watch: {
        userInfo(val) {
            if (!val.uid || !val.openId) {
                if (this.$store.state.config.forceLogin) {
                    wx.navigateTo({ url: "/pages/Login/Login" });
                } else {
                }
            }
        }
    },
    onShow() {
        wx.hideTabBar();
    },
    methods: {
        ...mapGetters(["customBar", "statusBar", "clientRect"]),
        getLikeVideo(uid) {
            this.$http.get("/mpGetLike", { uid }).then(res => {
                if (res.code == "001") {
                    this.$store.commit("SET_LIKE", res.list);
                }
            });
        },
        init() {
            let userInfo = wx.getStorageSync("userInfo");
            if (userInfo && userInfo.openId && userInfo.uid) {
                let userStatus = this.$store.state.userStatus;
                this.getLikeVideo(userInfo.uid);
                let now = Date.now();
                if (
                    userStatus &&
                    userStatus.startTime < now &&
                    userStatus.endTime > now
                ) {
                    $Toast({
                        content: `ئالى ئەزا ${wx
                            .getStorageSync("userInfo")
                            .nickName.slice(
                                0,
                                6
                            )} ، كىرگىنىڭىزنى قارشى ئالىمىز`,
                        icon: "success",
                        mask: false
                    });
                }
            }
            let formId = wx.getStorageSync("setForm");
            if (formId && Date.now() < formId.endTime) {
                this.signVisible = false;
            } else {
                this.signVisible = true;
            }
        },
        getFormId(e) {
            if (!this.$store.state.userInfo.openId) {
                $Toast({
                    content: "ئاۋۋال كىرىڭ",
                    mask: true
                });
                return;
            }
            let formId = e.detail.formId;
            let { openId, uid } = wx.getStorageSync("userInfo");
            try {
                this.$http
                    .get("/mpSetFormId", {
                        formId,
                        openId,
                        uid
                    })
                    .then(res => {
                        this.signVisible = false;
                        let dt = new Date(Date.now() + 1000 * 60 * 60 * 24);
                        let endTime = new Date(
                            `${dt.getFullYear()}-${dt.getMonth() +
                                1}-${dt.getDate()}`
                        ).valueOf();
                        wx.setStorageSync("setForm", {
                            startTime: dt.valueOf(),
                            endTime
                        });
                        this.updateUserInfo();
                        $Toast({
                            content: 2 + " " + res.msg,
                            icon: "success"
                        });
                        setTimeout(() => {
                            $Toast.hide();
                        }, 1500);
                    });
            } catch (error) {
                $Toast({
                    content: res.msg,
                    icon: "fail"
                });
                setTimeout(() => {
                    $Toast.hide();
                }, 1500);
            }
        },
        // 更新用户数据
        updateUserInfo() {
            let userInfo = wx.getStorageSync("userInfo");
            if (userInfo && userInfo.uid) {
                this.$http
                    .get("/mpGetUserStatus", { uid: userInfo.uid })
                    .then(res => {
                        if (res.code == "001") {
                            let infoStr = _decrypt(res.data, "yusupturak");
                            infoStr = Base64.decode(infoStr);
                            let info = JSON.parse(infoStr);
                            // 判断后端是否传了isVip字段
                            if (info && typeof info == "object" && info.isVip) {
                                this.$store.commit("SET_USER", info);
                            } else {
                                let now = Date.now();
                                if (
                                    info.startTime &&
                                    info.startTime < now &&
                                    info.endTime > now
                                ) {
                                    info.isVip = 1;
                                    {
                                        this.$store.commit("SET_USER", info);
                                    }
                                } else {
                                    this.$store.commit("SET_USER", info);
                                }
                            }
                        }
                    });
            }
        },
        getMore(query) {
            if (query == "new" || query == "hot") {
                wx.navigateTo({
                    url: "/pages/VideoList/VideoList?from=home&type=" + query
                });
            } else {
                wx.navigateTo({
                    url: "/pages/VideoList/VideoList?from=sort&sort=" + query
                });
            }
        },
        toAd(item) {
            if (item.type == 1 || item.type == 0) {
                wx.setStorageSync("AD", item);
                wx.navigateTo({ url: "/pages/AD/AD" });
            }
            if (item.type == 2) {
                wx.navigateToMiniProgram({
                    appId: item.adUrl, //要打开的小程序 appId,
                    path: "", //打开的页面路径，如果为空则打开首页,
                    success: res => {}
                });
            }
            if (item.type == 3) {
                let info = JSON.parse(item.adUrl);
                wx.navigateTo({
                    url: `/pages/Player/Player?vid=${info.vid}&type=${info.type}&sort=MOVIE`
                });
            }
            if (item.type == 4) {
                wx.navigateTo({ url: item.adUrl });
            }
        },
        async getAdList() {
            try {
                let list;
                if (this.$store.state.adList.length) {
                    list = this.$store.state.adList;
                    this.adList = list;
                } else {
                    let res = await this.$http.get("/getSwiper");
                    this.$store.commit("SET_CONF", {
                        canPlay: res.canPlay, //电影可否播放
                        iosPay: res.iosPay, //IOS付款
                        forceLogin: res.forceLogin, //强制登陆
                        lockPay: res.lockPay,
                        showAd: res.showAd
                    });
                    list = res.list;
                    this.adList = list;
                    this.$store.commit("SET_ELAN", res.elan);
                    this.elan = res.elan;
                    this.$store.commit("SET_AD", res.list);
                }

                // 判断用户是否登陆
                let userInfo = wx.getStorageSync("userInfo");
                if (userInfo && userInfo.openId && userInfo.uid) {
                    this.$store.commit("SET_USERINFO", userInfo);
                } else {
                    if (res.forceLogin) {
                        wx.navigateTo({ url: "/pages/Login/Login" });
                    } else {
                    }
                }
            } catch (error) {}
        },
        onScroll(e) {
            this.scroll = e;
        },
        fnThrottle(fn, delay, atleast, e) {
            let timer = null;
            let previous = null;
            return function() {
                let now = +new Date();
                if (!previous) previous = now;
                if (atleast && now - previous > atleast) {
                    fn(e);
                    previous = now;
                    clearTimeout(timer);
                } else {
                    clearTimeout(timer);
                    timer = setTimeout(function() {
                        fn(e);
                        previous = null;
                    }, delay);
                }
            };
        },
        toMyAd() {
            let elan = this.elan;
            if (elan.type == 1 || elan.type == 0) {
                wx.setStorageSync("AD", elan);
                wx.navigateTo({ url: "/pages/AD/AD" });
            }
            if (elan.type == 2) {
                wx.navigateToMiniProgram({
                    appId: elan.adUrl, //要打开的小程序 appId,
                    path: "", //打开的页面路径，如果为空则打开首页,
                    success: res => {}
                });
            }
            if (elan.type == 3) {
                wx.navigateTo({
                    url: `/pages/Player/Player?vid=${elan.vid}&elan.type=${elan.videoType}&sort=MOVIE`
                });
            }
            if (elan.type == 4) {
                wx.navigateTo({ url: elan.adUrl });
            }
        }
    },
    onShareAppMessage() {
        return {
            title: "مارس كىنوخانىسى",
            path: `/pages/Home/Home`,
            success: res => {
                console.log("share-success");
            },
            fail: () => {
                console.log("share-fail");
            },
            complete: () => {}
        };
    },
    onLoad() {
        let { uid } = this.$root.$mp.query;
        this.$store.commit("SET_SHARE_UID", uid);
    }
};
</script>

<style lang="scss" scoped>
.container {
    font-family: "ALKATIP UI";
    overflow: hidden;
    margin-bottom: 100rpx;
    .swiper-wrap {
        border-radius: 25rpx;
        width: 98%;
        margin: 0 auto;
        // overflow: hidden;
        margin-top: 10rpx;
        image {
            width: 100%;
            height: 100%;
            border-radius: 25rpx;
        }
    }
    .new-video,
    .hot-video,
    .recommend,
    .tv,
    .short-video,
    .show {
        width: 98%;
        margin: 0 auto;
        .list {
            display: grid;
            grid-template-columns: 32% 32% 32%;
            grid-column-gap: 15rpx;
        }
        .more {
            height: 58rpx;
            display: flex;
            justify-content: space-between;
            width: 96%;
            margin: 0 auto;
            color: #123;
            margin-top: 13rpx;
            border-bottom: 1px solid #eee;
            margin-bottom: 8rpx;
            box-shadow: 0 0 20rpx 1rpx rgba(0, 0, 0, 0.1);
            border-radius: 18rpx;
            padding: 0 15rpx;
            padding-bottom: 5rpx;
            .title {
                display: inline-block;
                line-height: 63rpx;
                transform: scaleY(0.8);
                font-size: 33rpx;
            }
            .dot {
                font-size: 28rpx;
                display: inline-block;
                line-height: 57rpx;
                .myfont {
                    font-size: 23rpx;
                }
                .name {
                    margin-right: 5rpx;
                }
                i {
                    display: inline-block;
                }
            }
        }
    }
    .show {
        // margin-bottom: 80rpx;
        margin-bottom: 150rpx;
    }
}
.sign-in {
    position: fixed;
    right: 5vw;
    bottom: 20vh;
    animation: mymove 2s cubic-bezier(0.73, -0.74, 1, 0.86) 0.5s infinite
        alternate;
    box-shadow: 0 0 15rpx 5rpx rgba(0, 0, 0, 0.15);
    border-radius: 50%;
    form {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;

        button {
            color: #f5f5f5;
            width: 90rpx;
            height: 90rpx;
            line-height: 90rpx;
            background-image: linear-gradient(
                90deg,
                #ffb821 0,
                #ff5c38 45%,
                #ff1459
            );
            border-radius: 50%;
            padding: 0;
            i {
                font-size: 31rpx;
                transform: scaleY(0.8);
            }
        }
    }
    &:active {
        animation-play-state: paused;
        transform: scale(1.1);
    }
}
@keyframes mymove {
    0% {
        bottom: 20vh;
    }
    100% {
        bottom: 22vh;
    }
}
.my-ad {
    position: fixed;
    top: 43%;
    left: 50%;
    transform: translateX(-50%) translateY(-43%);
    width: 600rpx;
    height: 400rpx;
    // border: 1px solid #333;
    // background-color: #123;
    border-radius: 30rpx;
    .elan {
        width: 100%;
        border-radius: 30rpx;
        height: 100%;
    }
    .exit {
        position: absolute;
        right: -33rpx;
        top: -34rpx;
        width: 50rpx;
        height: 50rpx;
        z-index: 2;
        opacity: 0.7;
        // background-image: url('https://mars-kino.oss-cn-beijing.aliyuncs.com/static/%E5%85%B3%E9%97%AD.png')
    }
}
</style>
